package top.smallway.NetWork;

import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;


public class Bank {
    private final String CSRFToken;
    private final OkHttpClient client;

    public Bank(String csrfToken) {
        CSRFToken = HttpUtil.get(urlBuild("/gettoken/"));
        client = new OkHttpClient().newBuilder().build();
    }


    public JSONObject loginBand(String UserID, String PasswordHash) {
        final String TAG = "登录网络请求";
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("UserID", UserID)
                .addFormDataPart("PasswordHash", PasswordHash)
                .build();
        Request request = new Request.Builder().url(urlBuild("/atm/login"))
                .method("POST", body)
                .addHeader("X-CSRFToken", CSRFToken).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                if (response.body() != null) {
                    return JSON.parseObject(response.body().string());
                }
            }
        } catch (IOException e) {
            Log log = LogFactory.get();
            log.error(e, TAG);
        }
        return new JSONObject();
    }

    public JSONObject withdraw(String UserID, float money) {
        final String TAG = "取钱";
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("UserID", UserID).addFormDataPart("money", String.valueOf(money)).build();
        Request request = new Request.Builder().url(urlBuild("/atm/withDraw")).method("POST", body).addHeader("X-CSRFToken", CSRFToken).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                if (response.body() != null) {
                    return JSON.parseObject(response.body().string());
                }
            }
        } catch (IOException e) {
            Log log = LogFactory.get();
            log.error(e, TAG);
        }
        return new JSONObject();
    }

    private String urlBuild(String api) {
        String URL = "https://bs.smallway.top";
        return URL.concat(api);
    }


}
